/**
 * \class CDiscoveryService
 * \brief This is a service to register distributed services in the cube cluster
 * \brief and to provide the references to discovery proxies.
 * \version 0.3.2
 *
 * \author Woo-Hyun Kim (woorung@nhncorp.com, woorung@gmail.com)
 * \author http://blog.naver.com/wisereign .
 *
 * \date 2007/10/8
 */
#ifndef CDiscoveryServiceH
#define CDiscoveryServiceH
//-----------------------------------------------------------------
#include <iostream>

#include "common_discovery.h"
#include "thread/CThread.h"
#include "service/CService.h"

using namespace std;
//-----------------------------------------------------------------
class CPurgeThread : public CThread
{
private:
	CSpace *service_space;

	int sleep_time;

	void run() {
		while(1) {
            		if(sleep_time<0) break;

			try {
				service_space->purge();

				sleep(sleep_time);
			} catch (InterruptedException& e) {
				cout << "[interrupt]" << getName() << ": " << e.what();
				break;
			} catch(IllegalThreadStateException& ie) {
				cout << "[illegal state]" << getName()<< ": " << ie.what();
				break;
			}
		}

		cout << "###" << getName() << " finished." << endl;
	}

public:
	CPurgeThread(char *name) {
		setName(name);

		sleep_time = 5;
	}
	virtual ~CPurgeThread() {
	}

	void setSpace(CSpace *space) {
		service_space = space;
	}
	
	void setSleepTime(int sleeptime) {
		sleep_time = sleeptime;
	}

	int getSleepTime() {
		return sleep_time;
	}
};
//-----------------------------------------------------------------
class CDiscoveryService : public CService
{
private:
        CSpace *service_space;

protected:
	CPurgeThread *purge_thread;

	void purge();
	
	int registry(CObjectArray *&objs, CObjectArray *&pobjs);
	int discovery(CObjectArray *&objs, CObjectArray *&pobjs);

public:
        CDiscoveryService(char *name);
        CDiscoveryService(const CDiscoveryService &rhs);
        ~CDiscoveryService(); 

        CDiscoveryService *clone() const; 
        CDiscoveryService &operator=(const CDiscoveryService &rhs);
	
        void run(cube__CObject *in, struct cube__invokeResponse &res);
};
//-----------------------------------------------------------------
#endif
